'use client';

// 文件夹选择对话框组件
// REF: API-NETDISK-003@v1.0

import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { ScrollArea } from '@/components/ui/scroll-area';
import {
  FolderOpen,
  Folder,
  ChevronRight,
  ChevronDown,
  Home,
  RefreshCw,
  Check
} from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import { DriveApiService } from './driveApi';

interface FolderItem {
  id: number;
  name: string;
  parentId: number | null;
  fullPath: string;
  isFolder: boolean;
  children?: FolderItem[];
  expanded?: boolean;
  loading?: boolean;
}

interface FolderSelectDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onConfirm: (folderId?: number, folderPath?: string) => void;
  defaultSelectedId?: number;
}

const STORAGE_KEY = 'import_last_selected_folder';

export function FolderSelectDialog({
  open,
  onOpenChange,
  onConfirm,
  defaultSelectedId
}: FolderSelectDialogProps) {
  const { toast } = useToast();
  const [folders, setFolders] = useState<FolderItem[]>([]);
  const [selectedFolderId, setSelectedFolderId] = useState<number | null>(null);
  const [selectedFolderPath, setSelectedFolderPath] = useState<string>('/');
  const [loading, setLoading] = useState(false);
  const [expandedFolders, setExpandedFolders] = useState<Set<number>>(new Set());

  // 从本地存储加载上次选择的文件夹
  useEffect(() => {
    if (open) {
      const lastSelected = localStorage.getItem(STORAGE_KEY);
      if (lastSelected) {
        try {
          const { folderId, folderPath } = JSON.parse(lastSelected);
          setSelectedFolderId(folderId);
          setSelectedFolderPath(folderPath);
        } catch (e) {
          // 忽略解析错误
        }
      } else if (defaultSelectedId) {
        setSelectedFolderId(defaultSelectedId);
      }
      loadRootFolders();
    }
  }, [open, defaultSelectedId]);

  // 加载根目录文件夹
  const loadRootFolders = async () => {
    setLoading(true);
    try {
      const response = await DriveApiService.listFiles(
        null, // parentId
        true, // foldersOnly
        1,    // page
        100   // pageSize
      );
      
      console.log('API Response:', response);
      
      // 处理API响应数据结构
      const apiData = response.data || response;
      const items = apiData.items || [];
      
      const rootFolder: FolderItem = {
        id: 0,
        name: '根目录',
        parentId: null,
        fullPath: '/',
        isFolder: true,
        children: items.map((item: any) => ({
          id: item.id,
          name: item.name,
          parentId: item.parentId,
          fullPath: item.fullPath || `/${item.name}`,
          isFolder: item.isFolder,
          children: [],
          expanded: false
        })),
        expanded: true
      };
      
      setFolders([rootFolder]);
      
      // 如果没有选中的文件夹，默认选中根目录
      if (!selectedFolderId) {
        setSelectedFolderId(0);
        setSelectedFolderPath('/');
      }
    } catch (error: any) {
      toast({
        title: '加载文件夹失败',
        description: error.message || '无法加载文件夹列表',
        variant: 'destructive'
      });
    } finally {
      setLoading(false);
    }
  };

  // 加载子文件夹
  const loadSubFolders = async (parentId: number, parentPath: string) => {
    try {
      const response = await DriveApiService.listFiles(
        parentId === 0 ? null : parentId, // parentId
        true, // foldersOnly
        1,    // page
        100   // pageSize
      );
      
      // 处理API响应数据结构
      const apiData = response.data || response;
      const items = apiData.items || [];
      
      const subFolders = items.map((item: any) => ({
        id: item.id,
        name: item.name,
        parentId: item.parentId,
        fullPath: item.fullPath || `${parentPath}/${item.name}`,
        isFolder: item.isFolder,
        children: [],
        expanded: false
      }));
      
      return subFolders;
    } catch (error: any) {
      toast({
        title: '加载子文件夹失败',
        description: error.message || '无法加载子文件夹',
        variant: 'destructive'
      });
      return [];
    }
  };

  // 切换文件夹展开状态
  const toggleFolder = async (folderId: number, folderPath: string) => {
    const updateFolderInTree = (folders: FolderItem[]): FolderItem[] => {
      return folders.map(folder => {
        if (folder.id === folderId) {
          if (!folder.expanded && folder.children?.length === 0) {
            // 需要加载子文件夹
            folder.loading = true;
            loadSubFolders(folderId, folderPath).then(subFolders => {
              setFolders(prevFolders => {
                const updateWithSubFolders = (folders: FolderItem[]): FolderItem[] => {
                  return folders.map(f => {
                    if (f.id === folderId) {
                      return {
                        ...f,
                        children: subFolders,
                        expanded: true,
                        loading: false
                      };
                    }
                    if (f.children) {
                      return { ...f, children: updateWithSubFolders(f.children) };
                    }
                    return f;
                  });
                };
                return updateWithSubFolders(prevFolders);
              });
            });
          } else {
            folder.expanded = !folder.expanded;
            folder.loading = false;
          }
        }
        if (folder.children) {
          folder.children = updateFolderInTree(folder.children);
        }
        return folder;
      });
    };
    
    setFolders(updateFolderInTree(folders));
    
    // 更新展开状态
    const newExpanded = new Set(expandedFolders);
    if (newExpanded.has(folderId)) {
      newExpanded.delete(folderId);
    } else {
      newExpanded.add(folderId);
    }
    setExpandedFolders(newExpanded);
  };

  // 选择文件夹
  const selectFolder = (folderId: number, folderPath: string) => {
    setSelectedFolderId(folderId);
    setSelectedFolderPath(folderPath);
  };

  // 确认选择
  const handleConfirm = () => {
    if (selectedFolderId !== null) {
      // 保存到本地存储
      localStorage.setItem(STORAGE_KEY, JSON.stringify({
        folderId: selectedFolderId,
        folderPath: selectedFolderPath
      }));
      
      onConfirm(selectedFolderId, selectedFolderPath);
      onOpenChange(false);
    }
  };

  // 渲染文件夹树
  const renderFolderTree = (folders: FolderItem[], level = 0) => {
    return folders.map(folder => (
      <div key={folder.id} className="select-none">
        <div
          className={`flex items-center gap-2 p-2 rounded cursor-pointer hover:bg-gray-50 ${
            selectedFolderId === folder.id ? 'bg-blue-50 border border-blue-200' : ''
          }`}
          style={{ paddingLeft: `${level * 20 + 8}px` }}
          onClick={() => selectFolder(folder.id, folder.fullPath)}
        >
          {/* 展开/收起按钮 */}
          <div className="w-4 h-4 flex items-center justify-center">
            {folder.children && folder.children.length > 0 ? (
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  toggleFolder(folder.id, folder.fullPath);
                }}
                className="hover:bg-gray-200 rounded p-0.5"
              >
                {folder.loading ? (
                  <RefreshCw className="h-3 w-3 animate-spin" />
                ) : folder.expanded ? (
                  <ChevronDown className="h-3 w-3" />
                ) : (
                  <ChevronRight className="h-3 w-3" />
                )}
              </button>
            ) : (
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  toggleFolder(folder.id, folder.fullPath);
                }}
                className="hover:bg-gray-200 rounded p-0.5"
              >
                {folder.loading ? (
                  <RefreshCw className="h-3 w-3 animate-spin" />
                ) : (
                  <ChevronRight className="h-3 w-3" />
                )}
              </button>
            )}
          </div>
          
          {/* 文件夹图标 */}
          {folder.id === 0 ? (
            <Home className="h-4 w-4 text-blue-600" />
          ) : folder.expanded ? (
            <FolderOpen className="h-4 w-4 text-blue-600" />
          ) : (
            <Folder className="h-4 w-4 text-blue-600" />
          )}
          
          {/* 文件夹名称 */}
          <span className="flex-1 text-sm">{folder.name}</span>
          
          {/* 选中标识 */}
          {selectedFolderId === folder.id && (
            <Check className="h-4 w-4 text-blue-600" />
          )}
        </div>
        
        {/* 子文件夹 */}
        {folder.expanded && folder.children && folder.children.length > 0 && (
          <div>
            {renderFolderTree(folder.children, level + 1)}
          </div>
        )}
      </div>
    ));
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl max-h-[80vh]">
        <DialogHeader>
          <DialogTitle>选择导入目标文件夹</DialogTitle>
          <DialogDescription>
            选择要将分享码文件导入到的虚拟网盘文件夹
          </DialogDescription>
        </DialogHeader>
        
        <div className="space-y-4">
          {/* 当前选择的路径 */}
          <div className="bg-gray-50 p-3 rounded">
            <div className="text-sm font-medium text-gray-700 mb-1">选中的文件夹路径：</div>
            <div className="font-mono text-sm text-blue-600">
              {selectedFolderPath || '/'}
            </div>
          </div>
          
          {/* 文件夹树 */}
          <ScrollArea className="h-96 border rounded p-2">
            {loading ? (
              <div className="flex items-center justify-center py-8">
                <RefreshCw className="h-6 w-6 animate-spin mr-2" />
                <span>加载文件夹中...</span>
              </div>
            ) : (
              <div className="space-y-1">
                {renderFolderTree(folders)}
              </div>
            )}
          </ScrollArea>
        </div>
        
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            取消
          </Button>
          <Button 
            onClick={handleConfirm}
            disabled={selectedFolderId === null}
          >
            确认导入
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

export default FolderSelectDialog;